package com.atyjh.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.dto.UserDTO;
import com.atyjh.reggie.entity.Employee;
import com.atyjh.reggie.mapper.EmployeeMapper;
import com.atyjh.reggie.service.IEmployeeService;
import com.atyjh.reggie.utils.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

import static com.atyjh.reggie.utils.RedisConstants.*;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.07
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<Employee> login(HttpSession session, String username, String password) {

//        1. 将密码使用MD5加密
        password = SecureUtil.md5(password);

//        2. 查询出对应员工信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, username).eq(Employee::getPassword, password);
        Employee employee = getOne(lqw);

//        3. 判断员工是否存在
        if (employee == null) {
            return Result.error("账号或密码错误!");
        }
//        4. 判断员工账户是否可用
        if (employee.getStatus() == 0) {
            return Result.error("该账号已被禁用，请联系管理员");
        }

//        5. 将员工信息封装成UserDTO,防止隐私信息泄露
        UserDTO user = new UserDTO();
        BeanUtil.copyProperties(employee, user);

////        6. 保存到ThreadLocal中（不好用呀...）
//        UserHolder.addUser(user);

//        6. 保存到Session域中
        session.setAttribute(LOGIN_USER_KEY, user);
        log.info("当前保存数据的线程为：" + Thread.currentThread());

//        7. 保存到Redis中
        String key = LOGIN_USER_KEY + user.getId();
        Map<String, Object> userMap = BeanUtil.beanToMap(user,
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
//        使用putAll()一次保存多个字段
        stringRedisTemplate.opsForHash().putAll(key, userMap);

//        设置三十分钟的过期时间
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.SECONDS);

//        8. 返回给前端账户信息
        return Result.success(employee);
    }

    @Override
    public Result<UserDTO> logout(HttpSession session) {
//        会有不同的线程来请求
//        UserDTO user = UserHolder.getUser();

        log.info("当前取数据的线程为：" + Thread.currentThread());

        UserDTO user = (UserDTO) session.getAttribute(LOGIN_USER_KEY);

        if (user == null) {
            return Result.error("用户不存在");
        }

        Long id = user.getId();
////        1. 将ThreadLocal中的用户信息移除
//        UserHolder.removeUser();
//        1.将Session中的数据移除
        session.removeAttribute(LOGIN_USER_KEY);

//        2. 将Redis中的用户信息移除
        stringRedisTemplate.delete(LOGIN_USER_KEY + id);

        return Result.success(null);
    }

    @Override
    public Result<String> saveEmployee(HttpServletRequest request, Employee employee) {
        UserDTO user = (UserDTO) request.getSession().getAttribute(LOGIN_USER_KEY);
        Long id = user.getId();

//        设置账号信息（不需要了，用了MP的自动填充）
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        employee.setPassword(SecureUtil.md5(INIT_PASSWORD));

        save(employee);
        return Result.success("新用户添加成功");
    }

    @Override
    public Result<Page<Employee>> pageEmployee(Integer page, Integer pageSize, String name) {

//        分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);

//        条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);

//        会自动把结果封装到pageInfo中，不用接收返回值
        page(pageInfo, lqw);

        return Result.success(pageInfo);
    }

    @Override
    public Result<String> update(HttpServletRequest request, Employee employee) {

        UserDTO user = (UserDTO) request.getSession().getAttribute(LOGIN_USER_KEY);

//        不需要了，使用了MP的自动填充字段功能
//        employee.setUpdateUser(user.getId());
//        employee.setUpdateTime(LocalDateTime.now());

        updateById(employee);

        return Result.success((employee.getStatus() == 1) ? "启用成功!" : "禁用成功!");
    }

}















